package com.itheima.Service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.CheckGroupDao;
import com.itheima.Service.CheckGroupService;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckItemDao;
import com.itheima.pojo.CheckGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private CheckItemDao checkItemDao;


    @Override
    public void add(List<Integer> checkItemIds, CheckGroup checkGroup) {

        checkGroupDao.add(checkGroup);
        Integer id = checkGroup.getId();
        this.setCheckItemCheckGroupId(checkItemIds,id);
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        checkGroupDao.deleteAssociation(id);
        checkGroupDao.deleteCheckGroupSemteal(id);
        checkGroupDao.delete(id);

    }

    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer id) {
        return checkGroupDao.findCheckGroupIdsBySetmealId(id);
    }

    @Override
    public PageResult findPage(QueryPageBean page) {
        PageHelper.startPage(page.getCurrentPage(),page.getPageSize());
        List<CheckGroup>checkGroups=checkGroupDao.findPage(page);
        Page<CheckGroup> checkGroups1=(Page<CheckGroup>)checkGroups;
        PageResult pageResult =new PageResult(((Page<CheckGroup>) checkGroups).getTotal(),checkGroups);
        return pageResult;
    }

    @Override
    @Transactional
    public void edit(CheckGroup checkGroup, List<Integer> checkitemIds) {
        Integer id=checkGroup.getId();
        //删除检查项和检查组关系
        checkGroupDao.deleteAssociation(id);
        //更新检查组
        checkGroupDao.updateCheckGroup(checkGroup);
        //添加检查项和检查组关系
        for (Integer checkitemId : checkitemIds) {
            checkGroupDao.editCheckGroupCheckItem(checkGroup.getId(),checkitemId);
        }

    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    private void setCheckItemCheckGroupId(List<Integer> checkItemIds,Integer id){
        System.out.println(checkItemIds);
        for (Integer checkItemId : checkItemIds) {
            checkGroupDao.setCheckItemCheckGroupId(checkItemId,id);
        }
    }



}
